/**
 * Created by qijialin on 2016/12/29.
 * 工艺路径
 */

var findCraftUrl = serverPath + 'RecipePath/findRecipePath';
var craftDetailUrl = serverPath + 'RecipePath/getRecipePathDetail';
var craftAddUrl = serverPath + 'RecipePath/addRecipePath';
var craftCopyUrl = serverPath + 'RecipePath/copyRecipePath';
var craftDeleteUrl = serverPath + 'RecipePath/deleteRecipePath';
var craftEditUrl = serverPath + 'RecipePath/updateRecipePath';
var craftVersionUpUrl = serverPath + 'RecipePath/upgradeRecipePath';
var craftCopyDivIndex = 0;
var craftAddDivIndex = 0;
var craftFlowEditDivIndex = 0;
var craftVersionUpDivIndex = 0;

//版本相关的
var ObjHistoryUrl = serverPath + 'versionHistory/queryVersionHistoryByTypeIdAndObjectId';
var ObjVersionChangeUrl = serverPath + 'versionHistory/queryVersionHistoryById';
var ObjVersionChangeStatusUrl = serverPath + 'versionProcess/queryOptionalState';
var ObjVersionAddVersionHistoryUrl = serverPath + 'versionHistory/addVersionHistory';
var craftVersionDetailDivIndex = 0;
var craftVersionHistoryDivIndex = 0;
var craftVersionChangeDivIndex = 0;

var craftTypeId = 5;

//加载时运行
$(function(){
    Init();

    //搜索工艺路径按钮事件
    $('#btnCraftSearch').click(function () {
        var condition = $('#txtCraftCondition').val();
        FindData(condition);
    });

    //工艺路径列表数据行 选中 事件 on Check
    $('#CraftList').on('check.bs.table', function (e, row){
        //拿到行选中的数据
        var craftId = row["id"];
        //刷新右边的数据显示
        LoadCraftDetail(craftId);
        LoadCraftPic(craftId);
    });

    //添加 工艺路径 按钮事件
    $('#btnCraftAdd').click(function () {
        var divUrl = "CraftWorkAdd.html";
        craftAddDivIndex = ibcpLayer.ShowDiv(divUrl, '添加工艺路径', '350px', '400px', function () {
            ListenCraftAddEvents();
        });
    });

    //拷贝 工艺路径 按钮事件
    $('#btnCraftCopy').click(function () {
        var divUrl = "CraftWorkCopy.html";
        craftCopyDivIndex = ibcpLayer.ShowDiv(divUrl, '复制工艺路径', '350px', '400px', function () {
            ListenCraftCopyEvents();
        });
    });

    //删除 工艺路径 按钮事件
    $('#btnCraftDelete').click(function () {
        var craftSel = $('#CraftList').bootstrapTable('getSelections');
        var delId = craftSel[0].id;
        var delMsg = craftSel[0].code + '-' + craftSel[0].name + '-' + craftSel[0].version;

        ibcpLayer.ShowConfirm('您确定要删除工艺路径：' + delMsg, function(){
            CraftDeleteEvent(delId)
        });
    });

    //编辑 工艺路径描述 按钮事件  craftDescEdit
    $('#btnCraftDescEdit').click(function () {
            CraftDescEditEvent();
    });

    //查看 工艺路径版本详细 按钮事件
    $('#btnCraftVNow').click(function() {
        var url = "../Version/VersionDetailCheck.html";
        craftVersionDetailDivIndex = ibcpLayer.ShowDiv(url, '工艺路径版本详细信息', '400px', '380px',function() {
            $("#VersionDetailTable").bootstrapTable();
            var vsId = $("#craftVS").attr('vsId');
            LoadVersionDetailData(vsId);
        });
    });

    //查看 工艺路径版本历史 按钮事件
    $('#btnCraftVHistory').click(function() {
        var url = "../Version/ObjectVersionHistory.html";
        craftVersionHistoryDivIndex = ibcpLayer.ShowDiv(url, '工艺路径版本历史信息', '900px', '380px',function() {
            $("#VersionHistoryTable").bootstrapTable();
            var craftId = $("#craftCode").attr("craftId");
            LoadDataForObjHistory(craftId, craftTypeId);
        });
    });

    //变更 工艺路径版本状态 按钮事件
    $('#btnCraftVChange').click(function() {
        var url = "../Version/ObjectStateChange.html";
        craftVersionChangeDivIndex = ibcpLayer.ShowDiv(url, '工艺路径版本变更', '420px', '480px',function() {
            var verId = $("#craftVS").attr('vsId');
            LoadVCInfo(verId);
        });
    });

    //升级 工艺路径版本 按钮事件
    $('#btnCraftVUp').click(function() {
        var url = "CraftWorkVSUp.html";
        craftVersionUpDivIndex = ibcpLayer.ShowDiv(url, '工艺路径版本升级', '350px', '400px',function() {
            $('#CWUCode').val($('#craftCode').val());
            $('#CWUName').val($('#craftName').val());
            $('#CWUDesc').val($('#craftDesc').val());
            ListenCraftUpEvents();
        });
    });

    //编辑 工艺路径图 按钮事件 craftFlowEdit
    $('#btnCraftPicEdit').click(function () {
        var craftId = $("#craftCode").attr('craftId');
        var divUrl = "../Editor/WorkFlowEditor/ProcedureEidtor.html?workFlowId=" + craftId;
        var iframeWin = null;
        var divIndex = layer.open({
            //layer提供了5种层类型。可传入的值有：0（信息框，默认）；1（页面层）；2（iframe层）；3（加载层）；4（tips层）。
            // 若你采用layer.open({type: 1})方式调用，则type为必填项（信息框除外）
            type: 2,
            //动画
            anim: 5,
            //title ：String
            //title: ['文本', 'font-size:18px;']
            //title: false 不显示标题栏
            title: ['编辑工艺路径', 'font-size:18px;font-weight:bold;'],
            //是否固定弹出
            fix: false,
            //最大小化按钮
            maxmin: true,
            //控制点击弹层外区域关闭
            shadeClose: false,
            //窗口大小 area: ['400px', '500px'] or auto 自适应大小
            area: ['1200px', '750px'],
            //area: '350px',
            //iframe层的url
            //content: 'http://www.baidu.com',
            content: divUrl,
            //是否允许拉伸
            resize: false,
            //浏览器滚动条
            scrollbar: false,
            zIndex: layer.zIndex, //重点1
            success: function(layero, index){
                var body = layer.getChildFrame('body', index);
                iframeWin = window[layero.find('iframe')[0]['name']];
            },
            full: function () {
                iframeWin.Max();
            },
            cancel: function () {
                if(iframeWin.savedCheck()){
                    var sig = iframeWin.initUnloadEvent();        //提示是否需要保存
                    return false;
                    return sig;
                }
            },
            end: function(){}
        });

        // craftFlowEditDivIndex = ibcpLayer.ShowIframe(divUrl, '编辑工艺路径图', '1200px', '600px',true, function (layero, index){
        //     // var body = layer.getChildFrame('body', index);
        //     var iframeWin = window[layero.find('iframe')[0]['name']];
        //     // console.log(body.html());
        //     console.log(iframeWin);
        //     iframeWin.test();
        // });
    });
});

/*****************************************************   初始化   ****************************************************/

//窗口调整大小事件
$(window).resize(function(){
    initPageSize();
});

//初始化
function Init(){
    initPageSize();
    InitBtnStatus();
    InitData();
}

//页面布局初始化
function initPageSize(){
    $('#right2').css('height', $('#leftDiv').height() -  212);
    $('#CraftEditor').css('height', $('#right2').height() -  50);
    var dataHeight = $('#leftDiv').height() -  100;
    $('#CraftList').bootstrapTable('refreshOptions',{height:dataHeight});
}

//初始化显示数据
function InitData(){
    var condition = $('#txtCraftCondition').val();
    FindData(condition);
}

//初始化 按钮状态
function InitBtnStatus(){
    $('#btnCraftAdd').attr("disabled", false);
    $('#btnCraftCopy').attr("disabled", true);
    $('#btnCraftDelete').attr("disabled", true);
    $('#btnCraftVNow').attr("disabled", true);
    $('#btnCraftVHistory').attr("disabled", true);
    $('#btnCraftVChange').attr("disabled", true);
    $('#btnCraftVUp').attr("disabled", true);
    $('#btnCraftDescEdit').attr("disabled", true);
    $('#btnCraftPicEdit').attr("disabled", true);
}


function ClearCraftData(){
    $("#craftCode").val("");
    $("#craftName").val("");
    $("#craftVS").val("");
    $("#craftStatus").val("");
    $("#craftDesc").val("");
    $('#CraftEditor').attr("src","");
    $("#craftDesc").attr("disabled", true);
}


function SetCraftRowStyle(row, index) {
    var strclass = "";
    if (row.statusName == '失效') {
        return { css: {"color": "#7f7f7f"}};
    }
    else {
        return {};
    }

}


/*****************************************************   搜索工艺路径   ****************************************************/

//查找数据
function FindData(str){
    InitBtnStatus();
    var datas = {'str':str};
    ibcpAjax.Select(findCraftUrl,datas,true,function(result){
        var data = result.data;
        $('#CraftList').bootstrapTable('load', data);
        if(data.length >0) {
            //设置选中行
            $('#CraftList').bootstrapTable('check', 0);
        }
        else {
            ClearCraftData();
        }

    });
}

function LoadCraftDetail(craftId){
    var datas = {'id':craftId};
    ibcpAjax.Select(craftDetailUrl,datas,true,function(result) {
        var data = result.data;
        var status = data["statusName"];
        $("#craftCode").val(data["code"]);
        $("#craftCode").attr('craftId', data["id"]);
        $("#craftName").val(data["name"]);
        $("#craftVS").val(data["version"]);
        $("#craftVS").attr('vsId', data["verId"]);
        $("#craftStatus").val(status);
        $("#craftDesc").val(data["description"]);


        $('#btnCraftCopy').attr("disabled", false);
        $('#btnCraftVNow').attr("disabled", false);
        $('#btnCraftVHistory').attr("disabled", false);
        $('#btnCraftVChange').attr("disabled", false);
        $('#btnCraftVUp').attr("disabled", false);

        if(status == "失效"){
            $('#btnCraftVChange').attr("disabled", true);
        }

        if(status == "编辑"){
            $("#craftDesc").attr('readonly',false);
            $('#btnCraftDescEdit').attr("disabled", false);
            $('#btnCraftPicEdit').attr("disabled", false);
            $('#btnCraftDelete').attr("disabled", false);
            $("#craftDesc").attr("disabled", false);
        }
        else {
            $("#craftDesc").attr('readonly',true);
            $('#btnCraftDescEdit').attr("disabled", true);
            $('#btnCraftPicEdit').attr("disabled", true);
            $('#btnCraftDelete').attr("disabled", true);
            $("#craftDesc").attr("disabled", true);
        }
    });
}

function LoadCraftPic(craftId){
    //var url = "../Editor/WorkFlowEditor/ProcedureEidtor.html?workFlowId=" + craftId;

    var url = "../Editor/WorkFlowEditor/ProcedureCheck.html?workFlowId=" + craftId;
    $('#CraftEditor').attr("src",url);
}

/*****************************************************   添加 工艺路径   ****************************************************/
//订阅事件
function ListenCraftAddEvents(){
    $('#btnCraftAddOK').on('click', function (){
        CraftAddOkEvent();
    });

    $('#btnCraftAddCancel').on('click', function (){
        CraftAddCancelEvent();
    });
}

//添加 工艺路径 确认按钮事件
function CraftAddOkEvent(){
    //验证
    var aCode = $('#CWACode').val();
    var aName = $('#CWAName').val();
    var aDesc = $('#CWADesc').val();
    var aReason = $('#CWAReason').val();
    if(aCode == ''){
        ibcpLayer.ShowTips("请输入代码！",$('#CWACode'));
        return;
    }
    if(aName == ''){
        ibcpLayer.ShowTips("请输入名称！",$('#CWAName'));
        return;
    }
    if(aReason == ''){
        ibcpLayer.ShowTips("请输入理由！",$('#CWAReason'));
        return;
    }
    //签名
    CallSign(100,function(sid){
        var datas = {'code':aCode,'name':aName,'description':aDesc,'reason':aReason,'sid':sid};
        ibcpAjax.Insert(craftAddUrl,datas,true,function(result){
            ibcpLayer.ShowOK('新增成功');
            var newId = result.data;
            //关闭签名
            SignCancel();
            //关闭新增
            CraftAddCancelEvent();
            //刷新定位新数据行
            GoToNewRow(newId);
        });
    })
}

function CraftAddCancelEvent(){
    ibcpLayer.Close(craftAddDivIndex);
}

//刷新定位新数据行
function GoToNewRow(newId){
    var sdatas = {'str':$('#txtCraftCondition').val()};
    ibcpAjax.Select(findCraftUrl,sdatas,true,function(results){
        var data = results.data;
        $('#CraftList').bootstrapTable('load', data);
        if(data.length >0) {
            //得到新增行数据
            var nowRow = $('#CraftList').bootstrapTable('getRowByUniqueId',newId);
            //var nowRow = $('#CraftList').bootstrapTable('getSelections');
            //移除新增行数据
            //$('#CraftList').bootstrapTable('remove', {field: 'id',values: newId});
            $('#CraftList').bootstrapTable('removeByUniqueId', newId);

            //将新增的数据放置在第一行
            $('#CraftList').bootstrapTable("prepend", nowRow);
            //定位新增行
            $("#CraftList").bootstrapTable("check", 0);
            //$("#CraftList").bootstrapTable("checkBy", {field:"id", values:[newId]});
        }
    });
}

/*****************************************************   拷贝 工艺路径   ****************************************************/
//订阅事件
function ListenCraftCopyEvents(){
    $('#btnCraftCopyOK').on('click', function (){
        CraftCopyOkEvent();
    });

    $('#btnCraftCopyCancel').on('click', function (){
        CraftCopyCancelEvent();
    });
}

//拷贝 工艺路径 确认按钮事件
function CraftCopyOkEvent(){
    var craftSel = $('#CraftList').bootstrapTable('getSelections');
    var oldId = craftSel[0].id;
    //验证
    var cCode = $('#CWCCode').val();
    var cName = $('#CWCName').val();
    var cDesc = $('#CWCDesc').val();
    var cReason = $('#CWCReason').val();
    if(cCode == ''){
        ibcpLayer.ShowTips("请填入代码！",$('#CWCCode'));
        return;
    }
    if(cName == ''){
        ibcpLayer.ShowTips("请填入名称！",$('#CWCName'));
        return;
    }
    if(cReason == ''){
        ibcpLayer.ShowTips("请填入理由！",$('#CWCReason'));
        return;
    }
    //签名
    CallSign(100,function(sid){
        var datas = {'oldId':oldId,'code':cCode,'name':cName,'description':cDesc,'reason':cReason,'sid':sid};
        ibcpAjax.Insert(craftCopyUrl,datas,true,function(result){
            ibcpLayer.ShowOK('拷贝成功');
            var newId = result.data;
            //关闭签名
            SignCancel();
            //关闭拷贝
            CraftCopyCancelEvent();
            //刷新定位新数据行
            GoToNewRow(newId);
        });
    })
}

//拷贝工艺路径取消事件
function CraftCopyCancelEvent(){
    ibcpLayer.Close(craftCopyDivIndex);
}

/*****************************************************   删除 工艺路径    ****************************************************/

function CraftDeleteEvent(delId){
    //签名
    CallSign(100,function(sid){
        var datas = {'id':delId,'sid':sid};
        ibcpAjax.Delete(craftDeleteUrl,datas,true,function(){
            SignCancel();
            ibcpLayer.ShowOK('删除成功');
            $('#btnCraftSearch').trigger('click');
        });
    })
}

/*****************************************************   编辑 工艺路径描述    ****************************************************/

function CraftDescEditEvent(){
    var craftSel = $('#CraftList').bootstrapTable('getSelections');
    var oldId = craftSel[0].id;
    var craftDesc = $('#craftDesc').val();

    CallSign(100,function(sid) {
        var datas = {'id': oldId, 'description': craftDesc, 'sid': sid};
        ibcpAjax.Update(craftEditUrl, datas, true, function () {
            ibcpLayer.ShowOK('保存成功');
            SignCancel();
        });
    });
}

/*****************************************************   查看 工艺路径版本详细    ****************************************************/

// 弹出 版本详细层 获取后台数据
function LoadVersionDetailData(id){
    'use strict';
    var datas = {'id': id};

    ibcpAjax.Select(ObjVersionChangeUrl, datas, true, function(result){
        var data = result.data;
        $('#Object_Detail_Version').val(data.version);
        $('#Object_Detail_Version').attr('readonly', 'readonly');
        $('#Object_Detail_State').val(data.toName);
        $('#Object_Detail_State').attr('readonly', 'readonly');
        $('#Object_Detail_StartTime').val(data.validStart);
        $('#Object_Detail_StartTime').attr('readonly', 'readonly');
        $('#Object_Detail_EndTime').val(data.validEnd);
        $('#Object_Detail_EndTime').attr('readonly', 'readonly');
        $('#Object_Detail_Operater').val(data.userName);
    });
}

function VSDetailClose(){
    layer.close(craftVersionDetailDivIndex);
}

/*****************************************************   查看 工艺路径版本历史    ****************************************************/
// 弹出层2获取后台数据
function LoadDataForObjHistory(objId, typeId){
    'use strict';
    var datas = {'objId': objId, 'typeId': typeId};

    ibcpAjax.Select(ObjHistoryUrl, datas, true, function(result){
        var data = result.data;
        $('#VersionHistoryTable').bootstrapTable('load', data);
    });
}

function VSHistoryClose(){
    layer.close(craftVersionHistoryDivIndex);
}
/*****************************************************   变更 工艺路径版本状态    ****************************************************/
//当前版本信息
var objNowVS = '';

//加载当前版本信息
function LoadVCInfo(vId){
    var datas = {'id': vId};
    ibcpAjax.Select(ObjVersionChangeUrl, datas, true, function(result) {
        objNowVS = result.data;
        $('#CurrentVersion').val(objNowVS.version);
        $('#CurrentStatus').val(objNowVS.toName);
        LoadAllowChangeStatusInfo(objNowVS.toStatusId, objNowVS.typeId);
    });
}

//加载可变更状态
function LoadAllowChangeStatusInfo(fromId, typeId){
    var datas = {'fromId': fromId,'typeId': typeId};
    $("#targetStatus").attr('readonly', true);
    $("#ValidDateStart").attr('readonly',true);
    $("#ValidDateEnd").attr('readonly',true);
    $("#ChangeReason").attr('readonly',true);
    $("#btnVCSave").attr('disabled',true);

    ibcpAjax.Select(ObjVersionChangeStatusUrl, datas, true, function(result){
        var data = result.data
        if(data.length > 0){
            $("#targetStatus").attr('readonly', false);
            $("#ValidDateStart").attr('readonly',false);
            $("#ValidDateEnd").attr('readonly',false);
            $("#ChangeReason").attr('readonly',false);
            $("#btnVCSave").attr('disabled',false);

            for(var i=0;i<data.length;i++) {
                var toOptions = "<option value='" + JSON.stringify(data[i]) + "'>" + data[i].toName + "</option>"
                $("#targetStatus").append(toOptions);
                $("#targetStatus").val('');
            }
            //只有一个数据的时候默认选择
            if(data.length == 1){
                $("#targetStatus").prop('selectedIndex', 0);
            }

        }
        else {
            ibcpLayer.ShowMsgCB('没有可变更的状态',function(){VSCCancel();});
        }
    });
}

//版本变更确认按钮事件
function VSCSave(){
    var vStart ='';
    var vEnd ='';
    var status = $("#targetStatus").val();
    var start = $("#ValidDateStart").val();
    var end = $("#ValidDateEnd").val();

    if(status == null || status == ""){
        ibcpLayer.ShowTips('请选择状态',$("#targetStatus"));
        return;
    }

    if(start != null && start != ""){
        vStart = start + ' 00:00:00';
    }

    if(end != null && end != ""){
        vEnd = end + ' 23:59:59';
    }

    if(vEnd != '' && vStart != ''){
        if(vEnd <= vStart){
            ibcpLayer.ShowTips('结束日期 早于 开始日期',$("#ValidDateEnd"));
            return;
        }
    }

    //var selectToInfo = status; //选择的目标状态信息 是字符串 需要转Json
    var selectToInfo = $.parseJSON(status); //选择的目标状态信息 是字符串 需要转Json

    var signNeedId = selectToInfo.aid;   //签名需要的ID
    var toId = selectToInfo.toId;         //目标状态ID
    var reason = $("#ChangeReason").val();

    CallSign(signNeedId,function(sid){
        var datas = {'verFlowId': objNowVS.verFlowId,
            'version': objNowVS.version,
            'fromStatusId': objNowVS.toStatusId,
            'toStatusId': toId,
            'validStart': vStart,
            'validEnd': vEnd,
            'sid': sid,
            'reason': reason,
            'objId': objNowVS.objId,
            'typeId': objNowVS.typeId
        };
        //保存
        ibcpAjax.Insert(ObjVersionAddVersionHistoryUrl,datas,false,function(result){
            SignCancel();
            ibcpLayer.Close(craftVersionChangeDivIndex);
            ibcpLayer.ShowOK("操作成功！");
            var craftId = $("#craftCode").attr('craftId');
            GoToNewRow(craftId);
            //LoadCraftDetail(craftId);
        });
    });
}

//版本变更取消按钮事件
function VSCCancel(){
    layer.close(craftVersionChangeDivIndex);
}
/*****************************************************   升级 工艺路径版本    ****************************************************/
//订阅事件
function ListenCraftUpEvents(){
    $('#btnCraftUpOK').on('click', function (){
        CraftUpOkEvent();
    });

    $('#btnCraftUpCancel').on('click', function (){
        CraftUpCancelEvent();
    });
}

//添加 工艺路径 确认按钮事件
function CraftUpOkEvent(){
    //验证
    var craftId = $('#craftCode').attr('craftId');
    var upReason = $('#CWUReason').val();

    if(upReason == ''){
        ibcpLayer.ShowTips("请填入理由！",$('#CWUReason'));
        return;
    }
    //签名
    CallSign(100,function(sid){
        var datas = {'id':craftId,'sid':sid, 'reason': upReason};
        ibcpAjax.Insert(craftVersionUpUrl,datas,true,function(result){
            ibcpLayer.ShowOK('升级成功');
            var newId = result.data;
            //关闭签名
            SignCancel();
            //关闭新增
            CraftUpCancelEvent();
            //刷新定位新数据行
            GoToNewRow(newId);
        });
    })
}

function CraftUpCancelEvent(){
    ibcpLayer.Close(craftVersionUpDivIndex);
}


/*****************************************************   编辑 工艺路径图    ****************************************************/

function InputRule(value){
    return value.replace(/[^\d]/g,'');
}